// 用于处理提高性能的函数

//防抖：连续触发事件的开始时立即执行一次，后连续触发不执行
function debounce(doSomething, wait, isImmediate) {
    var timeout;
    return function () {
        var _this = this,
            _arguments = arguments;
        clearTimeout(timeout);
        if (isImmediate) {
            var isTrigger = !timeout;
            timeout = setTimeout(function () {
                timeout = null;
            }, wait)
            isTrigger && doSomething.apply(_this, _arguments);
        } else {
            timeout = setTimeout(function () {
                doSomething.apply(_this, _arguments);
            }, wait);
        }
    }
}

//节流
function throttle(fn, threshhold = 160) {//默认160毫秒执行
    let timeout, start = new Date;
    return function () {
        let context = this, args = arguments, curr = new Date() - 0;
        clearTimeout(timeout)//总是干掉事件回调
        if (curr - start >= threshhold) {
            fn.apply(context, args); //threshhold毫秒后执行一次
            start = curr;
        } else {
            //让方法在脱离事件后也能执行一次
            timeout = setTimeout(function () {
                fn.apply(context, args)
            }, threshhold);
        }
    }
}

//开始时不执行，最后时间间隔内再执行一次。
function throttle2(doSomething, wait) {
    var timeout;
    return function () {
        var _this = this;
        _arguments = arguments;
        if (!timeout) {
            timeout = setTimeout(function () {
                timeout = null;
                doSomething.apply(_this, _arguments);
            }, wait);
        };
    }
}

export { debounce, throttle, throttle2 }